package com.adv.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.adv.mapper.UserMapper;
import com.adv.model.User;
import com.adv.util.EncryptorUtil;
import com.adv.util.SpringContextHolder;

// 当前没有用到，权限这块使用shiro处理了
public class LoginInterceptor extends HandlerInterceptorAdapter {

	public static final String USERSESSIONKEY = "u_s";
	public static final String USERCOOKIEKEY = "u_c";

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object bean) throws Exception {
		Object userSession = request.getSession().getAttribute(USERSESSIONKEY);
		logger.debug(String.format("user session is %s", userSession));
		logger.debug(String.format("request's uri is %s", request.getRequestURI()));
		if (userSession != null) {
			return true;
		}
		Cookie[] cookieArr = request.getCookies();
		if (null != cookieArr) {
			for (Cookie cookie : cookieArr) {
				if (USERCOOKIEKEY.equals(cookie.getName())) {
					try {
						String cookieValue = EncryptorUtil.decrypt(cookie.getValue());
						if (null != cookieValue) {
							// cookie is "name|id"
							String[] nameAndIdArr = cookieValue.split("\\|");
							if (nameAndIdArr.length == 2) {
								UserMapper mapper = SpringContextHolder.getBean(UserMapper.class);
								User user = mapper.selectByPrimaryKey(Integer.parseInt(nameAndIdArr[1]));
								request.getSession().setAttribute(USERSESSIONKEY, user);
								if ("/".equals(request.getRequestURI())) {
									response.sendRedirect("main");
								}
								return true;
							}
						}
					} catch (Exception e) {
						logger.warn(String.format("decrypt user cookie error:\r\ncookie's value is %s\r\nerror is %s",
								cookie.getValue(), e.getMessage()));
					}
					break;
				}
			}
		}
		// 不拦截/login页面，因为，可能用户勾选记住我，然后关闭浏览器后，再开启浏览器，这是打开/login页面，就获取不到session，虽然也可以从cookie获取登录信息，但是登录逻辑就麻烦了
		if (request.getRequestURI().contains("/login")) {
			return true;
		}
		logger.debug("user not login, now to login page!");
		response.sendRedirect("login");
		return false;
	}

}
